import { signal, batch } from "@preact/signals";
import { useLayoutEffect } from "preact/hooks";
import { getTime } from "../utilities";

const [n, y, r, s, f, m, nn, ny, nr, ns, x] = getTime();

const hundred = signal(n.slice(-4, 2));
const years = signal(n.slice(-2));
const months = signal(y);
const days = signal(r);
const hours = signal(s);
const minutes = signal(f);
const seconds = signal(m);
const nian = signal(nn);
const yue = signal(ny);
const ri = signal(nr);
const animal = signal(ns);
const week = signal(x);

const TimeDate = () => {
  useLayoutEffect(() => {
    const id = setInterval(() => {
      const [n, y, r, s, f, m, nn, ny, nr, ns, x] = getTime();
      batch(() => {
        hundred.value = n.slice(-4, 2);
        years.value = n.slice(-2);
        months.value = y;
        days.value = r;
        hours.value = s;
        minutes.value = f;
        seconds.value = m;
        nian.value = nn;
        yue.value = ny;
        ri.value = nr;
        animal.value = ns;
        week.value = x;
      });
    }, 500);
    return () => clearInterval(id);
  }, []);

  return (
    <div>
      <span class="countdown font-mono text-5xl">
        <span
          style={{ "--value": hours.value, "--digits": 2 }}
          aria-live="off"
          aria-label={hours}
        >
          {hours}
        </span>
        :
        <span
          style={{ "--value": minutes.value, "--digits": 2 }}
          aria-live="off"
          aria-label={minutes}
        >
          {minutes}
        </span>
        :
        <span
          style={{ "--value": seconds.value, "--digits": 2 }}
          aria-live="off"
          aria-label={seconds}
        >
          {seconds}
        </span>
      </span>
      <br />
      <span class="countdown font-mono text-xl">
        <span
          style={{ "--value": hundred.value }}
          aria-live="off"
          aria-label={hundred}
        >
          {hundred}
        </span>
        <span
          style={{ "--value": years.value }}
          aria-live="off"
          aria-label={years}
        >
          {years}
        </span>
        /
        <span
          style={{ "--value": months.value }}
          aria-live="off"
          aria-label={months}
        >
          {months}
        </span>
        /
        <span
          style={{ "--value": days.value }}
          aria-live="off"
          aria-label={days}
        >
          {days}
        </span>
      </span>
      <br />
      <span class="font-mono text-base">
        {nian}（{animal}）{yue}
        {ri}（{week}）
      </span>
    </div>
  );
};

export default TimeDate;
